<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">批量上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">批量下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" style="width: 100%;" height="500">
			<el-table-column type="selection" width="55" fixed>
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="title" label="标题" width="120">
			</el-table-column>
      <el-table-column prop="cover" label="封面" width="120">
        <template slot-scope="scope">
          <img :src="scope.row.cover" height="40" width="40"/>
        </template>
      </el-table-column>
			<el-table-column prop="saleprice" label="原价" width="180" sortable>
			</el-table-column>
      <el-table-column prop="costprice" label="售价" width="180" sortable>
      </el-table-column>
      <el-table-column prop="isnew" label="是否新车" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.isnew == 1" style="color: cadetblue;">是</span>
          <span v-if="scope.row.isnew == 0" style="color: yellowgreen;">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="reigstertime" label="上牌时间" width="180">
      </el-table-column>
      <el-table-column prop="mileage" label="里程数" width="180">
      </el-table-column>
      <el-table-column prop="shopname" label="店铺名称" width="180">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="180">
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="180">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: cadetblue;">上架</span>
          <span v-if="scope.row.state == 0" style="color: yellowgreen;">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="costeffective" label="是否超值" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.costeffective == 1" style="color: cadetblue;">是</span>
          <span v-if="scope.row.costeffective == 0" style="color: yellowgreen;">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="rushsale" label="是否急售" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.rushsale == 1" style="color: cadetblue;">是</span>
          <span v-if="scope.row.rushsale == 0" style="color: yellowgreen;">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="quasinewcar" label="是否准新车" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.quasinewcar == 1" style="color: cadetblue;">是</span>
          <span v-if="scope.row.quasinewcar == 0" style="color: yellowgreen;">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="transitivecountry" label="可迁全国" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.isnew == 1" style="color: cadetblue;">是</span>
          <span v-if="scope.row.isnew == 0" style="color: yellowgreen;">否</span>
        </template>
      </el-table-column>
      <el-table-column prop="carType.name" label="类型" width="100" sortable>
      </el-table-column>
      <el-table-column prop="seller.username" label="营销人员" width="100" sortable>
      </el-table-column>
      <el-table-column prop="auditstate" label="审核状态" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.auditstate == 0">待审核</span>
          <span v-if="scope.row.auditstate == 1">审核成功</span>
          <span v-if="scope.row.auditstate == 2">审核驳回</span>
        </template>
      </el-table-column>
			<el-table-column label="操作" width="150" fixed="right">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="danger" size="small" @click="handleResources(scope.$index, scope.row)">资源维护</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">上传检测报告</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="pageInfo.total"
          :current-page="query.currentPage"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--
		新增/修改界面
		-->
		<el-dialog title="新增/修改" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="carForm" label-width="80px" :rules="saveFormRules" ref="carForm">
        <el-form-item label="标题">
          <el-input v-model="carForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-preview="coverHandlePreview"
              :on-remove="coverHandleRemove"
              :on-success="coverHandleSuccess"
              :file-list="coverFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="carForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="carForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否新车">
          <el-radio-group v-model="carForm.isnew">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上牌时间">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="carForm.reigstertime"
              type="date"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="里程数">
          <el-input v-model="carForm.mileage" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="超值">
          <el-radio-group v-model="carForm.costeffective">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="急售">
          <el-radio-group v-model="carForm.rushsale">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="准新车">
          <el-radio-group v-model="carForm.quasinewcar">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可迁全国">
          <el-radio-group v-model="carForm.transitivecountry">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="车辆类型">
          <el-cascader v-model="carForm.type"
                       :options="carTypeTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="基本信息">
          <quill-editor v-model="carForm.carDetail.info" :options="quillOption">
          </quill-editor>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>

    <el-dialog title="资源维护" :visible.sync="carResourcesFormVisible" :close-on-click-modal="false">
      <el-form :model="carResourcesForm" label-width="80px" :rules="saveFormRules" ref="carForm">
        <el-form-item label="主图">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-preview="mainimgHandlePreview"
              :on-remove="mainimgHandleRemove"
              :on-success="mainimgHandleSuccess"
              :file-list="mainimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="副图">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-preview="subimgHandlePreview"
              :on-remove="subimgHandleRemove"
              :on-success="subimgHandleSuccess"
              :file-list="subimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="更多图片">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs/"
              :on-preview="moreimgHandlePreview"
              :on-remove="moreimgHandleRemove"
              :on-success="moreimgHandleSuccess"
              :file-list="moreimgFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carResourcesFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveCarResources" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from "../../common/js/quill-config.js"
	export default {
	  components:{
	    quillEditor
    },
		data() {
			return {
        quillOption:quillConfig,
				filters: {
					name: ''
				},
				listLoading: false,
				sels: [],//列表选中列

				saveFormVisible: false,//新增界面是否显示
				addLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入名字', trigger: 'blur' }
					]
				},
        coverFileList:[],
        mainimgFileList:[],
        subimgFileList:[],
        moreimgFileList:[],
        carTypeTree:[],
        //新增修改界面数据
        carForm: {
          id:null,
          title:"",
          cover:"",
          saleprice:0,
          costprice:0,
          isnew:0,
          reigstertime:"",
          mileage:null,
          costeffective:0,
          rushsale:0,
          quasinewcar:0,
          transitivecountry:0,
          type:{
            id:null,
            name:""
          },
          typeId:null,
          carDetail:{
            info:""
          }
        },
        query:{
				  currentPage:1,  // 当前页
          pageSize:10, // 每页显示条数
          keyword:""  // 关键字-查询条件
        },
        pageInfo:{
				  total:0,  // 总条数
          rows:[] // 当前页数据
        },
        carResourcesFormVisible:false,
        carResourcesForm:{
          carId:null,
          imgList:[]
        },
        mainimg:[],
        subimg:[],
        moreimg:[]
			}
		},
		methods: {
      onsale(){
        // this.sels 当前已选中的所有行 对象
        var ids = this.sels.map(item => item.id);
        //获取选中的行
        if(!this.sels || this.sels.length  <1){
          this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
          return;
        }
        this.$confirm('确认上架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post('/car/onsale',ids).then((res) => {
            this.listLoading = false;
            if(res.data.success){
              this.$message({
                message: '上架成功!'+res.data.message,
                type: 'success'
              });
              this.getCars();
            }else{
              this.$message({
                message: res.data.message,
                type: 'error'
              });
            }
            this.getpets();
          });
        }).catch(() => {

        });
      },
      offsale(){
        var ids = this.sels.map(item => item.id);
        //获取选中的行
        if(!this.sels || this.sels.length  <1){
          this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
          return;
        }
        this.$confirm('确认下架选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.post('/car/offsale',ids).then((res) => {
            this.listLoading = false;

            if(res.data.success){
              this.$message({
                message: '下架成功',
                type: 'success'
              });
            }else{
              this.$message({
                message: res.data.message,
                type: 'error'
              });
            }
            this.getpets();
          });
        }).catch(() => {

        });
      },
	    handleImgList(imgLists){
        if(imgLists && imgLists.length > 0){
          for(var i=0;i<imgLists.length;i++){
            this.carResourcesForm.imgList.push(imgLists[i]);
          }
        }
      },
      saveCarResources(){
          this.handleImgList(this.mainimg);
          this.handleImgList(this.subimg);
          this.handleImgList(this.moreimg);
          this.$http.post("/carResources/save",this.carResourcesForm)
              .then(result => {
                // 获取后端返回的结果
                result = result.data; // {success:true,message:""}
                if(result.success){
                  this.$message({message: "保存成功!",type: 'success'});
                  // 关闭弹框
                  this.carResourcesFormVisible = false;
                  // 关闭加载框
                  this.addLoading = false;
                  // 重新查询数据-(从当前页查询还是回到第一页,看需求)
                  this.query.currentPage = 1;
                  this.getCars();
                }else{
                  this.$message({message: result.message,type: 'error'});
                }
              })
              .catch(result => {
                this.$message({message: "网络异常,请检查网络!",type: 'error'});
              })
      },
      //主图文件上传成功回调  response,file 最近一次上传的文件对象  fileList 上传的所有的文件,数组
      mainimgHandleSuccess(response, file, fileList){
        this.mainimg = [];
          if(fileList && fileList.length > 0){
            for(var i=0;i<fileList.length;i++){
              var fileRes = fileList[i];
              //this.carResourcesForm.mainimg.push(fileRes.response.dataObj);
              // 因为从数据库查出来回显的数据,交给fileList以后,它里面没有response属性,所以取dataObj是会报错的
              var url = fileRes.response ? fileRes.response.dataObj : fileRes.url;
              this.mainimg.push({type:1,resourcesUrl:url})
            }
          }
      },
      //主图文件删除  fileList:删除后的文件列表
      mainimgHandleRemove(file, fileList) {
	      // 如果file.response为空,说明是数据库已有的图片,不能删除它在fastdfs里面的内容
	      if(!file.response){
          this.mainimgHandleSuccess(null,null,fileList)
          return;
        }
        var filePath = file.response.dataObj;
        this.$http.delete("/fastDfs?path="+filePath)
            .then(res=>{
              this.mainimgHandleSuccess(null,null,fileList)
              if(res.data.success){
                this.shop.logo = "";
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败!',
                  type: 'error'
                });
              }
            })
      },
      //主图图片预览
      mainimgHandlePreview(file) {
        console.log(file);
      },
      //副图文件上传成功回调  response,file 最近一次上传的文件对象  fileList 上传的所有的文件,数组
      subimgHandleSuccess(response, file, fileList){
        this.subimg = [];
        if(fileList && fileList.length > 0){
          for(var i=0;i<fileList.length;i++){
            var fileRes = fileList[i];
            //this.carResourcesForm.subimg.push(fileRes.response.dataObj);
            var url = fileRes.response ? fileRes.response.dataObj : fileRes.url;
            this.subimg.push({type:2,resourcesUrl:url})
          }
        }
      },
      //副图文件删除  fileList:删除后的文件列表
      subimgHandleRemove(file, fileList) {
        if(!file.response){
          this.subimgHandleSuccess(null,null,fileList)
          return;
        }
        var filePath = file.response.dataObj;
        this.$http.delete("/fastDfs?path="+filePath)
            .then(res=>{
              this.subimgHandleSuccess(null,null,fileList)
              if(res.data.success){
                this.shop.logo = "";
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败!',
                  type: 'error'
                });
              }
            })
      },
      //副图图片预览
      subimgHandlePreview(file) {
        console.log(file);
      },
      //更多图文件上传成功回调
      moreimgHandleSuccess(response, file, fileList){
        this.moreimg = [];
        if(fileList && fileList.length > 0){
          for(var i=0;i<fileList.length;i++){
            var fileRes = fileList[i];
            //this.carResourcesForm.moreimg.push(fileRes.response.dataObj);
            var url = fileRes.response ? fileRes.response.dataObj : fileRes.url;
            this.moreimg.push({type:3,resourcesUrl:url})
          }
        }
      },
      //更多图文件删除  fileList:删除后的文件列表
      moreimgHandleRemove(file, fileList) {
        if(!file.response){
          this.moreimgHandleSuccess(null,null,fileList)
          return;
        }
        this.$http.delete("/fastDfs?path="+filePath)
            .then(res=>{
              this.moreimgHandleSuccess(null,null,fileList)
              if(res.data.success){
                this.shop.logo = "";
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败!',
                  type: 'error'
                });
              }
            })
      },
      //更多图图片预览
      moreimgHandlePreview(file) {
        console.log(file);
      },
      // 点击资源维护按钮时触发
      handleResources(index,row){
        this.carResourcesFormVisible = true;
        this.carResourcesForm.carId = row.id;

        // 置空文件列表数组 是要解决 再次打开页面时,不要回显上次的数据
        this.mainimgFileList = [];
        this.subimgFileList = [];
        this.moreimgFileList = [];

        // 置空这三个数组,是为了避免将上一次上传的文件提交到后端
        this.mainimg = [];
        this.subimg = [];
        this.moreimg = [];

        // 根据carId到后端查询资源数据,然后赋值给前端的文件列表数组
        this.$http.get("/carResources/carId?carId="+row.id)
            .then(result => { // 后端操作成功,进入then()
              console.log(result);
              result = result.data;
              if(result.success){
                var list = result.dataObj;
                for(var i=0;i<list.length;i++){
                    var img = list[i];
                    var name = img.resourcesUrl.substring(img.resourcesUrl.lastIndexOf("/")+1)
                    // type =1 ,将url添加到mainimgList   并且还要添加到mainimg集合中
                  if(img.type == 1){
                    // [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
                    this.mainimgFileList.push({name: name, url: img.resourcesUrl});
                    this.mainimg.push(img);
                  }
                    // type =2 ,将url添加到subimgList  并且还要添加到subimg集合中
                  if(img.type == 2){
                    //this.subimgFileList.push(img.resourcesUrl);
                    this.subimgFileList.push({name: name, url: img.resourcesUrl});
                    this.subimg.push(img);
                  }
                    // type =3 ,将url添加到moreimgList  并且还要添加到moreimg集合中
                  if(img.type == 3){
                    //this.moreimgFileList.push(img.resourcesUrl);
                    this.moreimgFileList.push({name: name, url: img.resourcesUrl});
                    this.moreimg.push(img);
                  }
                }
              }else{ // false 说明后端处理失败
                this.$message({message: result.message,type: 'error'});
              }
            })
            .catch(result => {  // 如果报错 就会进入catch()
              this.$message({message: "网络异常,请检查网络!",type: 'error'});
            })
      },
      //文件上传成功回调
      coverHandleSuccess(response, file, fileList){
        this.carForm.cover = response.dataObj;
      },
      //文件删除
      coverHandleRemove(file, fileList) {
        var filePath = file.response.dataObj;
        this.$http.delete("/fastDfs?path="+filePath)
            .then(res=>{
              if(res.data.success){
                this.shop.logo = "";
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败!',
                  type: 'error'
                });
              }
            })
      },
      //图片预览
      coverHandlePreview(file) {
        console.log(file);
      },
      getCarsTree() {
        this.$http.get("/carType/tree")
            .then(result => { // 后端操作成功,进入then()
              console.log(result);
              result = result.data; // {success:true,message:"",dataObj:{}}
              if(result.success){ // true 后端返回了数据
                this.carTypeTree = result.dataObj;
              }else{ // false 说明后端处理失败
                this.$message({message: result.message,type: 'error'});
              }
            })
            .catch(result => {  // 如果报错 就会进入catch()
              this.$message({message: "网络异常,请检查网络!",type: 'error'});
            })
      },
      search(){
        // 将当前页设置为1
        this.query.currentPage = 1;
        this.getCars();
      },
			handleCurrentChange(val) {
        // 当 当前页的值被改变时触发
				// 将val(当前页)赋值给query.currentPage
        this.query.currentPage = val;
        // 调用查询方法,重新查询
				this.getCars();
			},
			//获取车辆列表
			getCars() {
        console.log(this.query)
        // 调用后端接口查询数据
        // "/car" 如果直接写这个路径,它默认是访问80的一个路径 需要需要在main.js中,引入axios时配置基本路径axios.defaults.baseURL
        // this.$http.post("/car"  = axios.baseURL+/car = http://localhost:8080/car
        this.$http.post("/car",this.query)
            .then(result => { // 后端操作成功,进入then()
              console.log(result);
              result = result.data; // {success:true,message:"",dataObj:{}}
              if(result.success){ // true 后端返回了数据
                this.pageInfo = result.dataObj;
              }else{ // false 说明后端处理失败
                this.$message({message: result.message,type: 'error'});
              }
            })
            .catch(result => {  // 如果报错 就会进入catch()
              this.$message({message: "网络异常,请检查网络!",type: 'error'});
            })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除这个数据吗?', '提示', {
					type: 'warning'
				}).then(() => {
					// 1 获取当前要删除数据的ID
          let id = row.id;
          // 2 调后端的删除接口
          this.$http.delete("/car/"+id)
                    .then(result => {
                        result = result.data; // {success:true,message:""}
                        if(result.success){
                          // 提示"删除成功"
                          this.$message({message: "删除成功!",type: 'success'});
                          // 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
                          this.query.currentPage = 1;
                          // 调用查询方法
                          this.getCars();
                          // this.search();
                        }else{
                          this.$message({message: result.message,type: 'error'});
                        }
                    })
                    .catch(result => {
                      this.$message({message: "网络异常,请检查网络!",type: 'error'});
                    })
				}).catch(() => {
          this.$message({message: '已取消删除!',type: 'info'});
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        // 展示弹框
				this.saveFormVisible = true;
				// 将当前行的对象赋值给this.saveForm对象
				this.saveForm = Object.assign({}, row);
        console.log(this.saveForm);
        // 特殊处理manager parent
        // 如果manager parent没有值,为null的话,就给它们赋一个初识对象
        if(!this.saveForm.manager){
          this.saveForm.manager = {
            id:null,
            username: ""
          }
        }
        // 级联下拉框要回显的话,它必须是个数组,如果你要展示到多少层,数组中就有几个id [1(一级部门的id),2(二级部门的id)]
        if(!this.saveForm.parent){
          this.saveForm.parent = {
            id:null,
            name: ""
          }
        }else{
          // this.saveForm.parent 不为空的时候,要单独处理,让级联下拉框回显 它需要的是当前部门的父部门的ID和父部门的父部门的id
          // 通过path组装id数组  比如说:/1/2/20  组装以后的数组:[1,2]  最后一级不要,因为最后一级表示的是当前部门自己本身,父部门这块是不需要展示自己的
          let array = this.saveForm.path.split("/");
          let temp = [];  // 装拼装后的数组
          for(let i=1;i<array.length-1;i++){
            temp.push(parseInt(array[i]));
          }
          console.log(temp)
          this.saveForm.parent = temp;
        }
        // 查询所有的员工信息,给employees赋值
        this.getAllEmployee();
        // 查询部门树,并赋值给deptTree
        this.getDeptTree();
			},
			//显示新增界面
			handleAdd: function () {
        // 显示弹框
				this.saveFormVisible = true;
				// 初始化弹框的值,为了防止将上次的内容带到了下一次
				this.carForm = {
          id:null,
          title:"",
          cover:"",
          saleprice:0,
          costprice:0,
          isnew:0,
          reigstertime:"",
          mileage:null,
          costeffective:0,
          rushsale:0,
          quasinewcar:0,
          transitivecountry:0,
          type:{
            id:null,
            name:""
          },
          carDetail:{
            info:""
          }
        }
        // 调用查询类型数方法
        this.getCarsTree();
			},
			//新增/修改的保存
			save: function () {
        // this.$refs.saveForm.validate((valid) => { 校验表单是否满足校验规则 valid=true 满足校验规则
				this.$refs.carForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true; // 加载框
                // 要处理传参
                let param = this.carForm;
                // 处理车辆类型
                var array = param.type;
                param.typeId = array[array.length-1];
                // 调用后端接口-axios
                this.$http.put("/car",param)
                    .then(result => {
                        // 获取后端返回的结果
                        result = result.data; // {success:true,message:""}
                        if(result.success){
                          this.$message({message: "保存成功!",type: 'success'});
                          // 关闭弹框
                          this.saveFormVisible = false;

                          // 关闭加载框
                          this.addLoading = false;

                          // 重新查询数据-(从当前页查询还是回到第一页,看需求)
                          this.query.currentPage = 1;
                          this.getCars();
                        }else{
                          this.$message({message: result.message,type: 'error'});
                        }
                    })
                    .catch(result => {
                      this.$message({message: "网络异常,请检查网络!",type: 'error'});
                    })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        // 1 获取选中的要删除行的ID
				var ids = this.sels.map(item => item.id);
        console.log(ids)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
          // 2 调后端的删除接口
          this.$http.patch("/car",ids)
              .then(result => {
                result = result.data; // {success:true,message:""}
                if(result.success){
                  // 提示"删除成功"
                  this.$message({message: "删除成功!",type: 'success'});
                  // 删除成功以后,要重新查询数据,并且要从第一页开始进行查询
                  this.query.currentPage = 1;
                  // 调用查询方法
                  this.getCars();
                  // this.search();
                }else{
                  this.$message({message: result.message,type: 'error'});
                }
              })
              .catch(result => {
                this.$message({message: "网络异常,请检查网络!",type: 'error'});
              })
				}).catch(() => {
          this.$message({message: '已取消删除!',type: 'info'});
				});
			}
		},
		mounted() {
		  // 挂载完毕,就要去后端查询分页数据并展示
			this.getCars();
		}
	}

</script>

<style scoped>

</style>